<template>
  <div class="divers-auditor-dialog">
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :show-close="true"
      :append-to-body="true"
      :fullscreen="false"
      :class="{'mobile-page-dialog':showMobilePage}"
      class="global-common-dialog auditor-dialog medium-common-dialog-size"
      @close="closeDialog"
    >
      <Title :title="title" font-size="16px" style="margin: 0 0 24px"/>
      <div v-if="dialogVisible" class="auditor-wrap">
        <div class="left-box">
          <auditor-pick
            :is-default-list="useDefaultList"
            :is-submit-btn="isSubmitBtn"
            :extend-params="extendParams"
            :default-user-list="defaultAduitorList"
            :max="maxLength"
            :examine-role-id="examineRoleId"
            :tag-selecteds.sync="tagSelecteds"
            :selected-auditors.sync="selectedAuditors"
            :include-leaver="includeLeaver"
            @refresh="refresh"/>
          <div class="btn-container">
            <el-button :loading="loading" :disabled="confirmBtnDisable" type="primary" size="small" @click="handleSubmit">
              确定<span v-if="maxLength !== Infinity">({{ selectedAuditors.length }}/{{ maxLength }})</span>
              <span v-else>({{ selectedAuditors.length }})</span>
            </el-button>
            <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose">取消</el-button>
          </div>
        </div>
        <div class="right-box">
          <default-auditor-select
            v-if="roleType === ROLE_TYPE.UNLIMITED || allowSelectOther"
            :max="maxLength"
            :tag-selecteds.sync="tagSelecteds"
            :init-diy-user-list="initDiyUserList"
            :selected-auditors.sync="selectedAuditors" />
          <custom-auditor-select
            v-else-if="[ROLE_TYPE.CREATOR, ROLE_TYPE.CUSTOMIZE, ROLE_TYPE.DIRECTOR, ROLE_TYPE.CREATOR_SUPERIOR, ROLE_TYPE.ROLE_GROUP].includes(roleType)"
            :is-submit-btn="isSubmitBtn"
            :extend-params="extendParams"
            :examine-role-id="examineRoleId"
            :max="maxLength"
            :tag-selecteds.sync="tagSelecteds"
            :selected-auditors.sync="selectedAuditors"
            @refresh="refresh"/>
          <dept-auditor-select v-else-if="roleType === ROLE_TYPE.DEPARTMENT" :department-list="departmentList" :max="maxLength" :tag-selecteds.sync="tagSelecteds" :selected-auditors.sync="selectedAuditors" />
          <custom-auditor-select v-else-if="[ROLE_TYPE.PROPOSER, ROLE_TYPE.AUTHUSER].includes(roleType)" :no-request="true" :default-list="defaultAduitorList" :examine-role-id="examineRoleId" :max="1" :tag-selecteds.sync="tagSelecteds" :selected-auditors.sync="selectedAuditors" />
          <custom-auditor-select v-else-if="[ROLE_TYPE.DESIGNATE, ROLE_TYPE.BP_APPROVER, ROLE_TYPE.DESIGNATE_DIRECTOR, ROLE_TYPE.ARREARS_USERS].includes(roleType)" :no-request="!isSubmitBtn && !isAddSigner" :is-submit-btn="isSubmitBtn" :default-list="defaultAduitorList" :extend-params="extendParams" :examine-role-id="examineRoleId" :max="maxLength" :tag-selecteds.sync="tagSelecteds" :selected-auditors.sync="selectedAuditors" @refresh="refresh" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import Title from '@/components/Title';
import DefaultAuditorSelect from './defaultAuditorSelect';
import AuditorPick from './auditorPick';
import CustomAuditorSelect from './customAuditorSelect';
import DeptAuditorSelect from './deptAuditorSelect';
import { ROLE_TYPE } from '@/utils/const/process';
import getAuditorList from '../mixins/getAuditorList';

export default {
  name: 'DiversAuditorDialog',
  components: { Title, DefaultAuditorSelect, AuditorPick, CustomAuditorSelect, DeptAuditorSelect },
  mixins: [getAuditorList],
  props: {
    isComfirm: {
      type: Boolean,
      default: false
    },
    isSubmitBtn: { // 入口是否从自定义提交按钮处来
      type: Boolean,
      default: false
    },
    extendParams: {
      type: Object,
      default: null
    },
    comfirmText: {
      type: String,
      default: ''
    },
    maxNum: {
      type: Number,
      default: 50
    },
    canEmpty: { // 是否允许人员为空
      type: Boolean,
      default: true
    },
    includeLeaver: { // 是否包含已离职人员
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      ROLE_TYPE,
      loading: false,
      userListLoading: false,
      dialogVisible: false,
      title: '选择人员',
      selectedAuditors: [], // 最终所选取的人员
      tagSelecteds: [], // 展示上用的选择内容 （可能是人 或者 部门）
      maxLength: 50,
      roleType: ROLE_TYPE.DEFAULT, // 0:任务创建人 1:选择部门 2:自定义人员 3:不限制审批人 4:申请人 5: 主管 6：任务发起节点（非角色，作为发起节点的判断值）
      tempData: null,
      examineRoleId: null,
      departmentList: null,
      confirmDisabled: false,
      defaultAduitorList: [],
      allowSelectOther: false,
      cache: null,
      isSelectSender: false, // 是否为审批更多操作选择抄送人
      isAddSigner: false, // 是否为添加加签人
      initAuditorList: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    confirmBtnDisable() {
      if (this.canEmpty) {
        return this.confirmDisabled;
      } else {
        return this.confirmDisabled || !this.selectedAuditors.length;
      }
    },
    useDefaultList() {
      // 指定人员/BP审批人/转交人选择在发起审批时不调用接口，审批同意确认时需要获取接口数据
      const roleArr = this.isSubmitBtn || this.isAddSigner ? [ROLE_TYPE.PROPOSER, ROLE_TYPE.AUTHUSER] : [ROLE_TYPE.DESIGNATE, ROLE_TYPE.BP_APPROVER, ROLE_TYPE.DESIGNATE_DIRECTOR, ROLE_TYPE.ARREARS_USERS, ROLE_TYPE.PROPOSER, ROLE_TYPE.AUTHUSER];
      return roleArr.includes(this.roleType) && !this.allowSelectOther;
    },
    initDiyUserList() {
      // 自定义人员如果选择了“允许选择其他人选项”，则在选择用户的第一页展示默认选中的那些人
      // 自定义人员、主管、创建人
      const auditorList = this.initAuditorList;
      if (this.allowSelectOther && auditorList && [ROLE_TYPE.CUSTOMIZE, ROLE_TYPE.DIRECTOR, ROLE_TYPE.CREATOR].includes(this.roleType)) {
        // 主管、创建人 需要先去请求接口才能拿到数据
        const cloneAuditorList = _.cloneDeep(auditorList);
        cloneAuditorList.forEach(i => {
          if (i.id) i.userId = i.id;
        });
        return [{ children: cloneAuditorList }];
      }
      return [];
    }
  },
  watch: {
    dialogVisible(val) {
      val && (this.confirmDisabled = false);
      if (!val) this.initAuditorList = [];
      this.$nextTick(() => {
        if (val && this.allowSelectOther && [ROLE_TYPE.CUSTOMIZE, ROLE_TYPE.DIRECTOR, ROLE_TYPE.CREATOR].includes(this.roleType) && this._getAutitorList) {
          this._getAutitorList();
        }
      });
    }
  },
  created() {
    this.maxLength = this.maxNum;
  },
  methods: {
    refresh() { // 刷新流程
      this.$emit('refresh');
    },
    handleClose() {
      localStorage.setItem('sendersLockIds', null);
      this.dialogVisible = false;
      this.isSelectSender = false;
    },
    closeDialog() {
      this.roleType = ROLE_TYPE.DEFAULT;
      this.selectedAuditors = [];
      this.tagSelecteds = [];
      this.examineRoleId = null;
      this.tempData = null;
      this.departmentList = null;
      this.$emit('closeDialog', this.cache);
    },
    handleSubmit() {
      if (this.isSelectSender) {
        this.handleSender();
      } else {
        this.handleOk();
      }
    },
    handleSender() {
      const selectUser = this.arrRepeat(this.selectedAuditors);
      this.$confirm('确认后，被抄送人将收到消息且拥有该审批可读权限', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: `del-message del-message-cancel ${this.showMobilePage ? ' mobile-message' : ''}`
      }).then(() => {
        this.$emit('handleSender', selectUser);
        this.handleClose();
        this.confirmDisabled = true;
      }).catch(() => {
        return false;
      });
    },
    handleOk() {
      const data = {
        tempData: this.tempData,
        selectUser: this.arrRepeat(this.selectedAuditors)
      };
      if (this.isComfirm) {
        this.$confirm(this.comfirmText, '', {
          confirmButtonText: '确定',
          type: 'warning',
          showClose: false,
          center: true,
          iconClass: 'charge-icon',
          customClass: `del-message del-message-cancel ${this.showMobilePage ? ' mobile-message' : ''}`
        }).then(() => {
          this.$emit('userSelect', data);
          this.handleClose();
          this.confirmDisabled = true;
        });
      } else {
        this.$emit('userSelect', data);
        this.handleClose();
        this.confirmDisabled = true;
      }
    },
    // 数组去重
    arrRepeat(data) {
      const hash = {};
      const data2 = data.reduce((preVal, curVal) => {
        if (!hash[curVal.id]) {
          hash[curVal.id] = true;
          preVal.push(curVal);
        }
        return preVal;
      }, []);
      return data2;
    },
    initData(params, title) {
      this.title = title;
      this.selectedAuditors = params.aduitors;
      this.tagSelecteds = params.aduitors;
      if ([ROLE_TYPE.PROPOSER, ROLE_TYPE.AUTHUSER].includes(params.roleType)) {
        this.defaultAduitorList = params.defaultAduitorList || [];
      }
      if ([ROLE_TYPE.DESIGNATE, ROLE_TYPE.BP_APPROVER, ROLE_TYPE.DESIGNATE_DIRECTOR, ROLE_TYPE.ARREARS_USERS].includes(params.roleType)) {
        this.defaultAduitorList = params.designateUsers || [];
      }
      this.examineRoleId = params.examineRoleId;
      this.allowSelectOther = params.allowSelectOther;
      this.departmentList = params.departmentList || [];
      this.tempData = params;
      this.roleType = params.roleType;
      this.cache = params.cache;
      this.isAddSigner = !!params.isAddSigner;
    },
    initSenderData(senders = [], title = '添加抄送人', maxLength) {
      this.examineRoleId = '';
      this.selectedAuditors = senders;
      this.tagSelecteds = senders;
      this.title = title;
      if (maxLength) this.maxLength = maxLength;
      this.roleType = ROLE_TYPE.UNLIMITED;
    },
    initDeliverTo(maxLength, title) {
      this.roleType = ROLE_TYPE.UNLIMITED;
      this.title = title;
      this.maxLength = maxLength;
      this.selectedAuditors = [];
      this.tagSelecteds = [];
    },
    // 审批流更多操作抄送
    initSelectSender() {
      this.dialogVisible = true;
      this.isSelectSender = true;
      this.initSenderData([], '添加抄送人', 1000);
    }
  }
};
</script>
<style lang="scss" scoped>
.auditor-dialog {
  & ::v-deep {
    .el-dialog {
      height: 556px;
    }
    .el-dialog__body {
      height: 100%;
    }
    .el-dialog__body {
      padding: 24px 10px 32px 24px !important;
    }
    .el-checkbox__label {
      padding-left: 16px;
    }
  }
  .btn-container{
    display: flex;
    flex-wrap: nowrap;
  }
  .auditor-wrap {
    display: flex;
    height: calc(100% - 40px);
    .left-box {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 0 24px 0 12px;
      border-right: 1px solid #EBEEFD;
    }
    .right-box {
      flex: 1;
      // padding: 0 0 0 24px;
    }
  }
}
.mobile-page-dialog {
  &::v-deep {
    .el-dialog {
      width: 100% !important;
      height: 400px !important;
      .el-dialog__close {
        right: -5px !important;
        top: -52px !important;
      }
      .el-dialog__body {
        padding-bottom: 40px !important;
      }
    }
    .dept-wrap,.auditor-pick-wrap,.role-wrap {
      height: 267px !important;
    }
    .tab-box {
      height: 288px !important;
      padding-left: 10px;
      .tab-btn {
        font-size: 14px !important;
        img {
          margin-right: 10px;
        }
      }
    }
    .content-header {
      font-size: 14px !important;
    }
  }
  .left-box {
    width: 100px;
    padding: 0 12px 0 0px !important;
  }
  .right-box {
    .tab-box {
      padding-left: 10px !important;
    }
  }
  .btn-container {
    position: absolute;
    bottom: 7px;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>
<style>
.el-dialog__headerbtn {
  z-index: 10;
}
</style>
